/**
 * Created by shawn on 17/8/23.
 */
const products = require('../service/product');
const stocks = require('../service/stock');
const news = require('../service/new');
var APIError = require('../rest').APIError;

module.exports = {
    'GET /api/products': async (ctx,next) =>{
        ctx.rest({
        products: products.getProducts()
    });
    },
    'POST /api/products': async (ctx,next) =>{
        var p = products.createProduct(ctx.request.body.name,
        ctx.request.body.manufacturer,
        parseFloat(ctx.request.body.price));
        ctx.rest(p);
    },
    'DELETE /api/products/:id': async(ctx,next)=>{
        console.log(`delete product ${ctx.params.id}...`);
        var p = products.deleteProduct(ctx.params.id);
        if(p){
            ctx.rest(p);
        }else{
            throw new APIError('product:not_found','product not found by id.');
        }
    },
    'GET /api/stocks':async (ctx,next) =>{
        ctx.rest(
            stocks.getStocks()
        );
    },
    'GET /api/stock/:id':async (ctx,next) =>{
        var stock = stocks.getStock(ctx.params.id);
        if(stock){
            ctx.rest(stock);
        }else{
            throw new APIError('stock:not_found','stock not found by id.');
        }
    },
    'POST /api/stocks':async(ctx,next) =>{
        var stock = stocks.createStock(ctx.request.body.name,
            parseFloat(ctx.request.body.price),
            ctx.request.body.rating,
            ctx.request.body.desc,
            ctx.request.body.categories);
        ctx.rest(stock);
    },
    'DELETE /api/products/:id':async(ctx,next)=>{
        console.log(`delete stock ${ctx.params.id}...`);
        var stock = stocks.deleteStock(ctx.params.id);
        if(stock){
            ctx.rest(stock);
        }else{
            throw new APIError('stock:not_found','stock not found by id.');
        }
    },
    'POST /api/new':async(ctx,next) =>{
        ctx.rest(
            news.getnews(ctx.request.body)
        );
    },
    'POST /api/createnew': async (ctx,next) =>{
        ctx.rest(
            news.createNews(ctx.request.body)
        );
    },
    'POST /api/updatenew': async (ctx,next) =>{
        ctx.rest(
            news.modifyNews(ctx.request.body)
        );
    },
    'DELETE /api/delnew/:id':async(ctx,next)=>{
        console.log(`delete stock ${ctx.params.id}...`);
        ctx.rest(
            news.deleteNews(ctx.params.id)
        );
    }
};